import router from '@/router'
import store from '@/store'
import nprogress from 'nprogress'
import 'nprogress/nprogress.css'
import { asyncRoutes } from '@/router'
/* 前置守卫 */
const whiteList = ['/login', '/404']
router.beforeEach(async(to, from, next) => {
  nprogress.start()
  console.log(store.getters.token)
  if (store.getters.token) {
    // console.log('有token')
    if (to.path === '/login') {
      next('/')
      nprogress.done()
    } else {
      if (!store.getters.userId) {
        const { roles } = await store.dispatch('user/getUserInfo')
        const filterRoutes = asyncRoutes.filter(item => {
          return roles.menus.includes(item.name)
        })// 筛选后的路由
        store.commit('user/setRoutes', filterRoutes)
        router.addRoutes([...filterRoutes, { path: '*', redirect: '/404', hidden: true }])
        next(to.path) // 这是vue-router的已知缺陷，需要重新执行要跳转的地址
      } else {
        next() // 放过
      }
    }
  } else {
    // 没有token 没有登陆
    if (whiteList.includes(to.path)) {
      // 在白名单 放行
      next()
    } else {
      next('/login') // 不在白名单 中转到登录页
      nprogress.done()
    }
  }
}
)
/* 后置守卫 */
router.afterEach(() => {
  console.log('1 2 3')
  nprogress.done()
})
